// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const routes = [
  {
    path: '/login',
    name: 'Login', 
    component: () => import('../views/Login.vue'),
    meta: { requiresGuest: true } // 仅未登录可访问
  },
  {
    path: '/',
    component: () => import('../layouts/AdminLayout.vue'),
    meta: { requiresAuth: true, roles: ['admin'] },
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import('../views/Home.vue'),
        meta: { roles: ['admin'] }
      },
      {
        path: 'products',
        name: 'ProductManage',
        component: () => import('../views/ProductManage.vue'),
        meta: { roles: ['admin'] }
      },
      {
        path: 'orders',
        name: 'OrderManage',
        component: () => import('../views/OrderManage.vue'),
        meta: { roles: ['admin'] }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue'),
        meta: { roles: ['admin'] }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 如果访问需要登录的页面
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    next('/login')
    return
  }
  
  // 检查角色权限
  if (to.meta.roles && authStore.isLoggedIn) {
    const userRole = authStore.user?.role
    if (!to.meta.roles.includes(userRole)) {
      // 权限不足，跳转到首页或显示提示
      next('/login')
      return
    }
  }
  
  // 如果访问仅限游客的页面（登录页）
  if (to.meta.requiresGuest && authStore.isLoggedIn) {
    next('/')
    return
  }
  
  next()
})

export default router